<template>
  <div>
    <h2>添加器材</h2>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/AdminMain/AdminHome">主页</el-breadcrumb-item>
      <el-breadcrumb-item to="/AdminMain/EquipmentManager">器材管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加器材</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <i class="el-icon-plus" style="margin-right: 5px;"></i>添加器材信息
        </div>
      </template>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="器材名称" prop="equipmentName">
          <el-input v-model="form.equipmentName" placeholder="请输入器材名称"/>
        </el-form-item>

        <el-form-item label="器材位置" prop="equipmentLocation">
          <el-input v-model="form.equipmentLocation" placeholder="请输入器材位置"/>
        </el-form-item>

        <el-form-item label="器材状态" prop="equipmentStatus">
          <el-input v-model="form.equipmentStatus" placeholder="请输入器材状态"/>
        </el-form-item>

        <el-form-item label="备注信息" prop="equipmentMessage">
          <el-input v-model="form.equipmentMessage" placeholder="请输入备注信息"/>
        </el-form-item>

        <el-form-item>
          <el-button type="success" @click="onSubmit">添加</el-button>
          <el-button @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {useRouter} from 'vue-router'
import axios from 'axios'
import {ElMessage} from 'element-plus'

const router = useRouter()

// 表单数据
const form = ref({
  equipmentName: '',
  equipmentLocation: '',
  equipmentStatus: '',
  equipmentMessage: ''
})

// 表单校验规则
const rules = {
  equipmentName: [{required: true, message: '请输入器材名称', trigger: 'blur'}],
  equipmentLocation: [{required: true, message: '请输入器材位置', trigger: 'blur'}],
  equipmentStatus: [{required: true, message: '请输入器材状态', trigger: 'blur'}],
  equipmentMessage: [{required: true, message: '请输入备注信息', trigger: 'blur'}]
}

const formRef = ref()

// 提交方法
const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      axios.post('/server/equipment/add', form.value)
          .then(response => {
            if (response.data.code === 200) {
              ElMessage.success('添加成功')
              router.push('/AdminMain/EquipmentManager')
            } else {
              ElMessage.error('添加失败: ' + response.data.message)
            }
          })
          .catch(() => {
            ElMessage.error('请求出错，无法添加器材')
          })
    }
  })
}

// 取消按钮
const onCancel = () => {
  router.push('/AdminMain/EquipmentManager')
}
</script>

<style scoped>
.card-header {
  font-weight: bold;
}
</style>
  